package com.xh.xyzp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xh.xyzp.common.constant.UserContext;
import com.xh.xyzp.common.domain.vo.resp.PageResp;
import com.xh.xyzp.common.enums.CommonStatusTypeEnum;
import com.xh.xyzp.domain.entity.Deliver;
import com.xh.xyzp.domain.entity.Job;
import com.xh.xyzp.domain.entity.Resume;
import com.xh.xyzp.domain.entity.User;
import com.xh.xyzp.domain.vo.DeliverPageReq;
import com.xh.xyzp.domain.vo.DeliverResp;
import com.xh.xyzp.domain.vo.DeliverSubmitReq;
import com.xh.xyzp.enums.DeliverStatusEnum;
import com.xh.xyzp.exception.ApiException;
import com.xh.xyzp.mapper.DeliverMapper;
import com.xh.xyzp.service.*;
import com.xh.xyzp.util.SnowFlakeIdWorker;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class DeliverServiceImpl extends ServiceImpl<DeliverMapper, Deliver> implements DeliverService {

    @Autowired
    private DeliverMapper deliverMapper;

    @Autowired
    private JobService jobService;

    @Autowired
    private ResumeService resumeService;

    @Autowired
    private JavaMailSender mailSender;


    @Override
    public void submit(DeliverSubmitReq req) {
        req.checkParams();
        if (Objects.isNull(req.getId())) {
            // 投递
            Job job = jobService.getById(req.getJobId());
            if (CommonStatusTypeEnum.BAN.getKey().equals(job.getStatus())) {
                throw new ApiException("职位已被禁用");
            }
            Deliver deliver = BeanUtil.copyProperties(req, Deliver.class);
            deliver.setId(new SnowFlakeIdWorker(1, 0).nextId());
            deliver.setUserId(UserContext.getUser().getId());
            deliver.setCompanyId(job.getCompanyId());
            deliver.setDeliverStatus(DeliverStatusEnum.DELIVER.getKey()); // 初始状态为待处理
            save(deliver);
        } else {
            // 状态改变
            boolean isStatusChange = Objects.nonNull(req.getDeliverStatus());
            Deliver deliver = deliverMapper.selectById(req.getId());
            deliver.setDeliverStatus(req.getDeliverStatus());
            updateById(deliver);
            if (isStatusChange) {
                sendEmil(deliver.getJobId(), deliver.getUserId(), deliver.getDeliverStatus());
            }
        }
    }

    @Async
    public void sendEmil(Long jobId, Long userId, Integer deliverStatus) {
        Job job = jobService.getById(jobId);
        Resume resume = resumeService.getInfoByUserId(userId);
        String htmlContent = "";
        if (deliverStatus.equals(DeliverStatusEnum.PASS.getKey())) {
            htmlContent = String.format(
                    "<html>" +
                            "<body style='font-family: Arial, sans-serif;'>" +
                            "  <div style='max-width: 600px; margin: 0 auto; padding: 20px;'>" +
                            "    <p>尊敬的 <strong>%s</strong>，</p>" +
                            "    <p>您申请职位：<strong>%s</strong>，已经面试通过</p>" +
                            "    <p>我们会尽快联系你，请耐心等待。</p>" +
                            "  </div>" +
                            "</body>" +
                            "</html>",
                    resume.getName(),
                    job.getName()
            );
        } else if (deliverStatus.equals(DeliverStatusEnum.INTERVIEW.getKey())) {
            htmlContent = String.format(
                    "<html>" +
                            "<body style='font-family: Arial, sans-serif;'>" +
                            "  <div style='max-width: 600px; margin: 0 auto; padding: 20px;'>" +
                            "    <p>尊敬的 <strong>%s</strong>，</p>" +
                            "    <p>您申请职位：<strong>%s</strong>，已经到面试流程</p>" +
                            "    <p>我们会尽快联系你，请耐心等待。</p>" +
                            "  </div>" +
                            "</body>" +
                            "</html>",
                    resume.getName(),
                    job.getName()
            );
        } else if (deliverStatus.equals(DeliverStatusEnum.FAILED.getKey())) {
            htmlContent = String.format(
                    "<html>" +
                            "<body style='font-family: Arial, sans-serif;'>" +
                            "  <div style='max-width: 600px; margin: 0 auto; padding: 20px;'>" +
                            "    <p>尊敬的 <strong>%s</strong>，</p>" +
                            "    <p>您申请职位：<strong>%s</strong>，面试未通过，已进入我司人才库，感谢你的关注</p>" +
                            "  </div>" +
                            "</body>" +
                            "</html>",
                    resume.getName(),
                    job.getName()
            );
        }
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom("2770063826@qq.com");
            helper.setTo(resume.getEmail());
            helper.setSubject("投递进度邮件");
            helper.setText(htmlContent, true);
            mailSender.send(message);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ApiException("邮件发送出错");
        }
    }

    @Override
    public PageResp<DeliverResp> getList(DeliverPageReq req) {
        req.checkParams();
        LambdaQueryWrapper<Deliver> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Deliver::getUserId, UserContext.getUser().getId());
        Page<Deliver> deliverPage = deliverMapper.selectPage(new Page<>(req.getCurrPage(), req.getPageSize()), lambdaQueryWrapper);
        return PageResp.<DeliverResp>builder()
                .list(deliverPage.getRecords().stream().map(item -> getInfo(item.getId())).collect(Collectors.toList()))
                .total(deliverPage.getTotal())
                .build();
    }

    @Override
    public DeliverResp getInfo(Long deliverId) {
        if (Objects.isNull(deliverId)) {
            throw new ApiException("id不能为空");
        }
        Deliver deliver = lambdaQuery()
                .eq(Deliver::getId, deliverId)
                .eq(Deliver::getStatus, CommonStatusTypeEnum.NORMAL.getKey())
                .one();
        Job job = jobService.getById(deliver.getJobId());
        DeliverResp deliverResp = BeanUtil.copyProperties(job, DeliverResp.class);
        UserService userService = SpringUtil.getBean(UserService.class);
        User user = userService.getById(deliver.getUserId());
        deliverResp.setUsername(user.getUsername());
        deliverResp.setDeliverStatus(deliver.getDeliverStatus());
        deliverResp.setNickname(user.getNickname());
        deliverResp.setDeliverId(deliver.getId());
        deliverResp.setResume(SpringUtil.getBean(ResumeService.class).getInfoByUserId(user.getId()));
        return deliverResp;

    }

    @Override
    public PageResp<DeliverResp> getAdminList(DeliverPageReq req) {
        req.checkParams();
        LambdaQueryWrapper<Deliver> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (Objects.nonNull(req.getDeliverStatus())) {
            lambdaQueryWrapper.eq(Deliver::getDeliverStatus, req.getDeliverStatus());
        }
        if (Objects.nonNull(req.getId())) {
            lambdaQueryWrapper.eq(Deliver::getId, req.getId());
        }
        lambdaQueryWrapper.eq(Deliver::getCompanyId, SpringUtil.getBean(CompanyService.class).getCompanyByUserId(UserContext.getUser().getId()).getId());
        Page<Deliver> deliverPage = deliverMapper.selectPage(new Page<>(req.getCurrPage(), req.getPageSize()), lambdaQueryWrapper);
        return PageResp.<DeliverResp>builder()
                .list(deliverPage.getRecords().stream().map(item -> getInfo(item.getId())).collect(Collectors.toList()))
                .total(deliverPage.getTotal())
                .build();
    }

} 